package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.core.entity.AddAiCheckEvent;
import com.xxl.job.executor.core.entity.AddAiEventImage;
import com.xxl.job.executor.core.utils.ApiUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、在Spring Bean实例中，开发Job方法，方式格式要求为 "public ReturnT<String> execute(String param)"
 * 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class HttpClientXxlJob {
    private static Logger logger = LoggerFactory.getLogger(HttpClientXxlJob.class);
    @Value( "${xxl.job.postIp}" )
    private String POSTIP;

    /**
     * 1、添加一条卡口检测记录
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob( "addAiCheckEvent" )
    public ReturnT<String> addAiCheckEvent(String param) throws Exception {
        String[] paramArr = param.split(";");
        String USERCODE = paramArr[0];
        String STATIONCODE = paramArr[1];
        String STATIONNAME = paramArr[2];
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("text/plan");
        String LaneNo = "1";
        String dateTime = new SimpleDateFormat("yyMMddHHmmssSSSS").format(new Date());
        AddAiCheckEvent addAiCheckEvent = new AddAiCheckEvent();
        addAiCheckEvent.setCheck_no(USERCODE + LaneNo + dateTime);
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        addAiCheckEvent.setVehicle_id("豫R" + String.valueOf(rannum).substring(0, 5));
        addAiCheckEvent.setVehicle_model_Id("10");
        addAiCheckEvent.setVehicle_model_name("轿车");
        addAiCheckEvent.setVehicle_color("蓝");
        addAiCheckEvent.setVehicle_type_id(new BigDecimal(4).setScale(2, BigDecimal.ROUND_HALF_UP));
        addAiCheckEvent.setVehicle_type("小型汽车");
        addAiCheckEvent.setBody_color("黑");
        addAiCheckEvent.setEvent_type_id(new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP));
        addAiCheckEvent.setEvent_type_name("逆行");
        addAiCheckEvent.setDirection("上行");
        addAiCheckEvent.setLane_no(new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP));
        addAiCheckEvent.setSpeed(new BigDecimal(35).setScale(2, BigDecimal.ROUND_HALF_UP));
        addAiCheckEvent.setCheck_time(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date()));
        addAiCheckEvent.setStation_id(USERCODE);
        addAiCheckEvent.setStation_name(STATIONNAME);
        addAiCheckEvent.setStation_code(STATIONCODE);
        String jsonData = JSON.toJSONString(addAiCheckEvent);
        RequestBody body = RequestBody.create(mediaType, jsonData);
        String eToken = ApiUtils.ClientGetCiphertext(USERCODE);
        String data = "hello";
        Request requestData = new Request.Builder()
                .url("http://" + POSTIP + "/ServiceAiEvent.svc/AI/AddAiCheckEvent?uc=" + USERCODE + "&et=" + eToken + "&data=" + data)
                .method("POST", body)
                .addHeader("Content-Type", "text/plan")
                .build();
        Response responseData = client.newCall(requestData).execute();
        XxlJobLogger.log("args = [" + body.toString() + "]");
        XxlJobLogger.log("args = [" + responseData.body().string() + "]");
        XxlJobLogger.log("XXL-JOB, 添加一条卡口检测记录.");
        //2、发送图片
        File file = new File("D:\\123456.jpg");
        String base64Img = ApiUtils.ConvertImageToBase64(file);
        AddAiEventImage addAiEventImage = new AddAiEventImage();
        addAiEventImage.setCheck_no(USERCODE + LaneNo + dateTime);
        addAiEventImage.setImg_type("1");  //图片标识 1：车头 2：车身 3：车牌 4: 车头2  5: 车尾
        addAiEventImage.setServer_ip("192.168.0.1");
        addAiEventImage.setServer_port("23");
        addAiEventImage.setServer_address(file.getPath());
        addAiEventImage.setFile_type(new MimetypesFileTypeMap().getContentType(file));
        addAiEventImage.setCreate_time(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date()));
        addAiEventImage.setImagefile(base64Img);
        String jsonImg = JSON.toJSONString(addAiEventImage);
        RequestBody bodyImg = RequestBody.create(mediaType, jsonImg);
        Request requestImg = new Request.Builder()
                .url("http://" + POSTIP + "/ServiceAiEvent.svc/AI/AddAiEventImage?uc=" + USERCODE + "&et=" + eToken + "&data=" + data)
                .method("POST", bodyImg)
                .addHeader("Content-Type", "text/plan")
                .build();
        Response responseImg = client.newCall(requestImg).execute();
        XxlJobLogger.log("args = [" + bodyImg.toString() + "]");
        XxlJobLogger.log("args = [" + responseImg.body().string() + "]");
        XxlJobLogger.log("XXL-JOB, 添加一张卡口过车检测的图片.");
        return ReturnT.SUCCESS;
    }
}
